import React, { useState, useEffect } from 'react';
import {
  Row,
  Col,
  Card,
  Statistic,
  Progress,
  List,
  Tag,
  Button,
  Space,
  Alert
} from 'antd';
import {
  DatabaseOutlined,
  ExperimentOutlined,
  CheckCircleOutlined,
  SyncOutlined
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import { analyticsAPI } from '../services/api.ts';

const Dashboard: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [datasets, setDatasets] = useState([]);
  const [jobs, setJobs] = useState([]);
  const [systemStats, setSystemStats] = useState({
    totalDatasets: 0,
    totalJobs: 0,
    runningJobs: 0,
    completedJobs: 0
  });

  useEffect(() => {
    fetchDashboardData();
    const interval = setInterval(fetchDashboardData, 30000); // Refresh every 30 seconds
    return () => clearInterval(interval);
  }, []);

  const fetchDashboardData = async () => {
    try {
      const [datasetsRes, jobsRes] = await Promise.all([
        analyticsAPI.getDatasets(),
        analyticsAPI.getJobs()
      ]);

      setDatasets(datasetsRes);
      setJobs(jobsRes);

      // Calculate statistics
      const stats = {
        totalDatasets: datasetsRes.length,
        totalJobs: jobsRes.length,
        runningJobs: jobsRes.filter(job => job.status === 'running').length,
        completedJobs: jobsRes.filter(job => job.status === 'completed').length
      };

      setSystemStats(stats);
      setLoading(false);
    } catch (error) {
      console.error('Failed to fetch dashboard data:', error);
      setLoading(false);
    }
  };

  const getJobStatusColor = (status: string) => {
    switch (status) {
      case 'completed':
        return 'success';
      case 'running':
        return 'processing';
      case 'failed':
        return 'error';
      default:
        return 'default';
    }
  };

  const getJobStatusIcon = (status: string) => {
    switch (status) {
      case 'completed':
        return <CheckCircleOutlined />;
      case 'running':
        return <SyncOutlined spin />;
      default:
        return null;
    }
  };

  // Chart configuration for job status distribution
  const jobStatusChart = {
    title: {
      text: 'Job Status Distribution',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: 'Jobs',
        type: 'pie',
        radius: '50%',
        data: [
          { value: systemStats.completedJobs, name: 'Completed' },
          { value: systemStats.runningJobs, name: 'Running' },
          { value: systemStats.totalJobs - systemStats.completedJobs - systemStats.runningJobs, name: 'Pending' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };

  // Chart configuration for dataset sizes
  const datasetSizeChart = {
    title: {
      text: 'Dataset Sizes',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: datasets.map(ds => ds.name)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: 'Samples',
        type: 'bar',
        data: datasets.map(ds => ds.shape?.n_samples || 0)
      }
    ]
  };

  return (
    <div>
      <Row gutter={[16, 16]}>
        {/* Statistics Cards */}
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="Total Datasets"
              value={systemStats.totalDatasets}
              prefix={<DatabaseOutlined />}
              loading={loading}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="Total Jobs"
              value={systemStats.totalJobs}
              prefix={<ExperimentOutlined />}
              loading={loading}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="Running Jobs"
              value={systemStats.runningJobs}
              prefix={<SyncOutlined spin={systemStats.runningJobs > 0} />}
              loading={loading}
              valueStyle={{ color: systemStats.runningJobs > 0 ? '#1890ff' : undefined }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="Completed Jobs"
              value={systemStats.completedJobs}
              prefix={<CheckCircleOutlined />}
              loading={loading}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
        {/* Charts */}
        <Col xs={24} lg={12}>
          <Card title="Job Status Distribution" loading={loading}>
            <ReactECharts
              option={jobStatusChart}
              style={{ height: '300px' }}
              opts={{ renderer: 'canvas' }}
            />
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card title="Dataset Sizes" loading={loading}>
            <ReactECharts
              option={datasetSizeChart}
              style={{ height: '300px' }}
              opts={{ renderer: 'canvas' }}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
        {/* Recent Jobs */}
        <Col xs={24} lg={12}>
          <Card
            title="Recent Jobs"
            extra={<Button type="link" href="/analytics">View All</Button>}
            loading={loading}
          >
            <List
              dataSource={jobs.slice(0, 5)}
              renderItem={(job) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={getJobStatusIcon(job.status)}
                    title={
                      <Space>
                        <span>{job.type}</span>
                        <Tag color={getJobStatusColor(job.status)}>
                          {job.status}
                        </Tag>
                      </Space>
                    }
                    description={`Dataset: ${job.input_dataset_id}`}
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>

        {/* Recent Datasets */}
        <Col xs={24} lg={12}>
          <Card
            title="Recent Datasets"
            extra={<Button type="link" href="/datasets">View All</Button>}
            loading={loading}
          >
            <List
              dataSource={datasets.slice(0, 5)}
              renderItem={(dataset) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={<DatabaseOutlined />}
                    title={dataset.name}
                    description={
                      <Space direction="vertical" size="small">
                        <span>{dataset.description || 'No description'}</span>
                        <Space>
                          <Tag>Samples: {dataset.shape?.n_samples || 0}</Tag>
                          <Tag>Dimensions: {dataset.shape?.n_dimensions || 0}</Tag>
                        </Space>
                      </Space>
                    }
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>

      {systemStats.runningJobs > 0 && (
        <Alert
          message="Jobs Running"
          description={`${systemStats.runningJobs} job(s) are currently being processed.`}
          type="info"
          showIcon
          style={{ marginTop: 16 }}
        />
      )}
    </div>
  );
};

export default Dashboard;